package com.gin.kotlin.no_gay_alliance.fragment.post

import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingFragment
import com.gin.kotlin.no_gay_alliance.base.FragmentStateContainer
import com.gin.kotlin.no_gay_alliance.databinding.FragmentPostEmojiBinding
import com.gin.kotlin.no_gay_alliance.model.emoji.GenericEmojiGroup
import com.gin.kotlin.no_gay_alliance.store.GlobalProperty
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator


class PostEmojiFragment : AbstractBindingFragment<FragmentPostEmojiBinding>(), TabLayoutMediator.TabConfigurationStrategy {
    private lateinit var tabLayoutMediator: TabLayoutMediator
    private lateinit var tabs: List<FragmentStateContainer>

    /**
     * onCreateView的后续操作 ，如通过  [FragmentActivity.addMenuProvider] 添加菜单
     */
    override fun onCreateView() {
        val b = this.b ?: return

        val dao = App.INSTANCE.database.emojiHistoryDao()

        val hiddenGroup = GlobalProperty.getInstance().hiddenGenericEmojiGroup
        // 表情分组标签
        this.tabs = App.INSTANCE.obtainGenericEmojiPackages()
            .mapNotNull { it.groups }.flatten().toMutableList()
            .also {
                // 最常使用
                it.add(0, GenericEmojiGroup("最常使用", data = dao.listByCount()?.map { d -> d.toModel() }))
                // 最近使用
                it.add(1, GenericEmojiGroup("最近使用", data = dao.listByTimestamp()?.map { d -> d.toModel() }))
            }
            // 过滤掉被设置为隐藏的分组
            .filter { !hiddenGroup.contains(it.getUniqueName()) }
            .map { group -> FragmentStateContainer(group.name) { PostEmojiTabFragment.newInstance(group) } }

        // 为ViewPager2设置适配器
        b.viewPager2.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount() = tabs.size
            override fun createFragment(position: Int) = FragmentStateContainer.newInstance(tabs, position)
        }
        this.tabLayoutMediator = attachTabLayout(b.tabLayout, b.viewPager2, this)

    }

    override fun onConfigureTab(tab: TabLayout.Tab, position: Int) {
        this.tabs[position].title?.also { tab.text = it }
    }
}